from fastapi import FastAPI, Response, BackgroundTasks
from fastapi.responses import StreamingResponse
from app.settings import settings
import random
import string
import pandas as pd
from io import BytesIO
import os
from app.models.admin import Downloads
from app.core.ctx import CTX_USER_ID


def random_filename():
    random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    return random_str

async def create_excel(name:str,data):
    # 创建一个 DataFrame
    df = pd.DataFrame(data)
    # 将 DataFrame 写入 BytesIO 对象
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Sheet1')
    # 将指针移动到开头
    output.seek(0)
    #生成文件
    path = random_filename()+".xlsx"
    url = os.path.join(settings.EXCEL_FOLDER + "/" + path)
    with open(url, 'wb') as f:
        f.write(output.getvalue())
    #写入数据库
    user_id = CTX_USER_ID.get()
    await Downloads.create(name=name,state=0,user_id=user_id,url=url)
    return True

def date_format(date):
    return date.strftime(settings.DATE_FORMAT)